//
//  HomeViewController.m
//  Doctors
//
//  Created by 王森 on 16/4/7.
//  Copyright © 2016年 王森. All rights reserved.
//

#import "HomeViewController.h"
#import "HomeDiTuiTableViewCell.h"
#import "HomeOrderTableViewCell.h"
#import "HomeHeaderView.h"
#import "MJRefresh.h"
#import "lhScanQCodeViewController.h"
#import "UIButton+Block.h"
#import "IncomeViewController.h"

#import <CoreLocation/CoreLocation.h>
#import "AppDelegate.h"
#import "OpenUDID.h"
#import "UIDevice+DeviceTypes.h"
#import "JPUSHService.h"

@interface HomeViewController ()<CLLocationManagerDelegate>
{
    NSString *_artisanId;
    
    NSString *_artisanName;
    NSString *_amount;
    NSString *_orderCount;
    
    NSDictionary *dicRecource;
    
    BOOL location;
    
    
}
@property(nonatomic,retain)CLLocationManager * locationManage;

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"--------======%@",[JPUSHService registrationID]);
    
    
    [self setTextTitleViewWithFrame:CGRectMake(0, 0, 60, 20) title:@"理大师" fontSize:18];
    _artisanId=[[TMCache sharedCache]objectForKey:@"artisanId"];
    _artisanName=[[TMCache sharedCache]objectForKey:@"artisanName"];
    
    self.title=@"首页";
    
    __weak typeof(self) weakSelf = self;
    
    [self setRightImageBarButtonItemWithFrame:CGRectMake(0, 0, 27, 24) image:@"nav_ icon_phone" selectImage:nil action:^(WRBButton *button) {
        [weakSelf phone:button];
        
    }];
    
    [self setLeftImageBarButtonItemWithFrame:CGRectMake(0, 0, 28, 23) image:@"nav_icon_saoyisao" selectImage:nil action:^(WRBButton *button) {
        [weakSelf saomiao:button];
        
    }];
    
    // 创建定位功能
    [self createGPSMap];
    
    [self customTableView];
    self.tableview.hidden=YES;
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self requestData];
        
        [self.tableview.mj_header endRefreshing];
        
    }];
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    self.tableview.mj_header.automaticallyChangeAlpha = YES;
    
    
    
    UINib *ordernib=[UIView loadNibNamed:@"HomeOrderTableViewCell" bundle:nil];
    [self.tableview registerNib:ordernib forCellReuseIdentifier:@"HomeOrderTableViewCell"];//注册cell
    UINib *DiTuinib=[UIView loadNibNamed:@"HomeDiTuiTableViewCell" bundle:nil];
    [self.tableview registerNib:DiTuinib forCellReuseIdentifier:@"HomeDiTuiTableViewCell"];
    
    dicRecource = [NSDictionary dictionary];
    
    [self requestData];
    
    /**
     *  上传激光参数
     */
    [self uploadPushRegisterMsg];
    
}


-(void)uploadPushRegisterMsg
{
    
    
    GlobalGCD(^{
        
        NSMutableDictionary *dic=[NSMutableDictionary dictionary];
        NSLog(@"deviceToken：%@",[JPUSHService registrationID]);
        if (!TARGET_IPHONE_SIMULATOR) {
            [dic setObject:[JPUSHService registrationID] forKey:@"registerId"];
            
        }
        
        [dic setObject:[self getArtisanId] forKey:@"artisanId"];
        [dic setObject:@"iOS" forKey:@"systemPlatform"];
        [dic setObject:[UIDevice service] forKey:@"systemVersion"];
        [dic setObject:[UIDevice machine] forKey:@"deviceMode"];
        [dic setObject:[OpenUDID value] forKey:@"Imei"];
        
        NSLog(@"上传激光参数%@",dic);
        
        [[WSNetworkApi shareManager]postWithUrl:@"/artisan/saveArtisanPushRegisterMsg" parameters:dic option:RequestCenterCachePolicyNormal sucess:^(id responseObject) {
            NSLog(@"上传激guang%@",responseObject);
            
        } failur:^(NSError *error) {
            NSLog(@"上传激guang%@",error);
            
        }];
        
    });
    
}


-(void)requestData
{
    
    [self addProgressHUD];
    
    
    NSDictionary *dictionary=[NSDictionary dictionaryWithObjectsAndKeys:_artisanId, @"artisanId", nil];
    [[WSNetworkApi shareManager]postWithUrl:@"/artisan/getArtisanInfo" parameters:dictionary option:RequestCenterCachePolicyNormal sucess:^(id responseObject) {
        [self removeStatuslable];
        
        
        NSLog(@"%@",responseObject);
        
        if ([responseObject[@"status"] isEqualToString:@"ok"]) {
            
            self.tableview.hidden=NO;
            
            _amount=[NSString stringWithFormat:@"%@", responseObject[@"artisan"][@"amount"]];
            _orderCount=[NSString stringWithFormat:@"%@", responseObject[@"artisan"][@"count"]];
            
            [[TMCache sharedCache]setObject:responseObject[@"artisan"][@"id"] forKey:@"artisanId"];
            [[TMCache sharedCache]setObject:responseObject[@"artisan"][@"name"]forKey:@"artisanName"];
            
            dicRecource = responseObject[@"artisan"];
            
            
            
        }
        
        [self.tableview reloadData];
        
    } failur:^(NSError *error) {
        NSLog(@"%@",error);
        
        [self removeStatuslable];
        
        [self.view makeToast:@"请检查您的网络"];
    }];
    
    
}
-(void)phone:(WRBButton *)btn
{
    
    [self callmobile: @"40068388987"];
    
    
    
}

-(void)saomiao:(WRBButton *)btn
{
    
    ALLOC(lhScanQCodeViewController, view);
    [self pushNextViewController:view];
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        return 224;
        
    }else
        return 200;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return 2;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    NSDictionary *dic = @{};
    
    if (section==0) {
        
        if (dicRecource[@"orderInfo"]!=dic) {
            return 1;
        }
        else
        {
            return 0;
        }
    }
    else{
        
        if (dicRecource[@"pushInfo"]!=dic) {
            return 1;
        }else
        {
            return 0;
        }
    }
    
    
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    
    if (section==0) {
        
        HomeHeaderView *headerView=[[HomeHeaderView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 189)];
        headerView.name.text=[NSString stringWithFormat:@"%@，欢迎回来",_artisanName];
        headerView.price.text=_amount;
        headerView.orderCount.text=_orderCount;
        [headerView.todayDetail addActionHandler:^(NSInteger tag) {
            
            ALLOC(IncomeViewController, view);
            view.hidesBottomBarWhenPushed=YES;
            [self pushNextViewController:view];
            
            
        }];
        
        
        return headerView;
        
    }
    else
    {
        return [UIView new];
        
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        return 189;
    }else
        return 0;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    __weak typeof(self)weakSelf=self;
    
    if (indexPath.section==0) {
        
        HomeOrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HomeOrderTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        [cell cellFuzhi:dicRecource];
        
        
        [cell setBoDaMobile:^(NSString *string){

            [weakSelf callmobile:string];
            
        }];
        
        
        [cell setChangeorderStatus:^(void)
         {
             NSLog(@"状态栏");

             [weakSelf requestData];
             
             
         }];
        
        return cell;
    }
    else{
        HomeDiTuiTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HomeDiTuiTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        [cell cellData:dicRecource];
        [cell.scanBtn addActionHandler:^(NSInteger tag) {
            ALLOC(lhScanQCodeViewController, view);
            [self pushNextViewController:view];
            
        }];
        
        [cell setBoDaMobile:^(NSString *string){
            
            [weakSelf callmobile:string];
            
        }];
        return cell;
    }
    
}



- (void)callmobile:(NSString *)sender{
    
    NSMutableString * strs=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",sender];
    //            NSLog(@"str======%@",str);
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strs]];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)createGPSMap
{
    
    //    2、在Info.plist文件中添加如下配置：
    //    （1）NSLocationAlwaysUsageDescription     YES
    //    （2）NSLocationWhenInUseUsageDescription     YES
    //初始化位置服务
    _locationManage = [[CLLocationManager alloc] init];
    
    //    设置定位精度
    _locationManage.desiredAccuracy = kCLLocationAccuracyBest ;
    //要求CLLocationManager 对象返回的全部数据
    _locationManage.distanceFilter = kCLDistanceFilterNone ;
    //IOS8以后需要添加
    //    [_locationManage requestAlwaysAuthorization];//一直可以调用
    [_locationManage requestWhenInUseAuthorization];//需要的事后调用
    
    _locationManage.delegate = self;
    [_locationManage startUpdatingLocation];
    [NSTimer scheduledTimerWithTimeInterval:300.0f target:self selector:@selector(openLocation) userInfo:nil repeats:YES];
}

#pragma mark - 定位所需要的协议
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(nonnull NSArray<CLLocation *> *)locations{
    CLLocation * newLocation = [locations lastObject];
    /**
     *  停止定位
     */
    
    /**
     *  取得经纬度
     */
    CLLocationCoordinate2D coord2D  = newLocation.coordinate ;
    double latitude = coord2D.latitude ;
    double longitude = coord2D.longitude;
    NSLog(@"纬度=%f  经度=%f",latitude,longitude);
    [self changeLocationLat:latitude AndLon:longitude];

    if (location) {
        [self changeLocationLat:latitude AndLon:longitude];
        location = NO;
    }
    [_locationManage stopUpdatingLocation];
    
}
- (void)changeLocationLat:(double)lat AndLon:(double)lon{
    
    
    NSString *latitude = [NSString stringWithFormat:@"%f", lat];
    NSString *longitude = [NSString stringWithFormat:@"%f", lon];
    
    
    NSDictionary *dictionary=[NSDictionary dictionaryWithObjectsAndKeys:_artisanId, @"artisanId", latitude, @"latitude", longitude, @"longitude", nil];
    [[WSNetworkApi shareManager]postWithUrl:@"/artisan/getArtisanInfo" parameters:dictionary option:RequestCenterCachePolicyNormal sucess:^(id responseObject) {
        NSLog(@"设置位置成功%@", responseObject);
        
    } failur:^(NSError *error) {
        
    }];
    
}


- (void)openLocation{
    [_locationManage startUpdatingLocation];
    location = YES;
}
- (void)dealloc{
    _locationManage = nil;
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
